<?php

namespace App\Http\Controllers\Site;
use App\B2BProject\Site\HelperControllerBuildTrait;
use Auth;
use App\B2BProject\Area;
use App\B2BProject\Custom\Business\GoodsCategory;
use App\B2BProject\Custom\Provider\CounterOffer;
use App\B2BProject\Custom\Provider\Offer;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Validator;

/**
 * 供应报盘
 * Class ProviderController
 * @package App\Http\Controllers\Site
 *
 */
class ProviderController extends Controller
{
    use HelperControllerBuildTrait;
    public function __construct()
    {
        parent::__construct();

        $this->middleware('auth', ['except' => ['getInfo', 'getList', 'getChoose']]);
     }

    /**
     * 搜索跳转
     * @param $cid
     * @param $pid
     * @return $this
     */
    public function getChoose($cid, $pid)
    {
        return view('host/free')->with('pid', $pid)->with('cid', $cid);
    }

    /**
     * 供应报盘
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function getList(Request $request)
    {
        $pid = 0;
        $cid='';
        $request->query->set('page', $request->query('page', $request->page));
        $request->query->set('pageSize', $request->query('pageSize', $request->pageSize));

        $query = Offer::orderBy('created_at','desc')->Available();
        if ($goodType = $request->query('goodType')) {
            $category = GoodsCategory::with('children')->whereId($goodType)->firstOrFail();
            if ($category->parent_id == 0) {
                $in = [];
                foreach ($category->children as $child) {
                    $in[] = $child->id;
                }

                $query = $query->whereIn('secondary_category_id', $in);
            } else {
                $query = $query->where('secondary_category_id', $goodType);
            }
        }
        $info = $query->paginate($request->query('pageSize', 7));

        if (\Request::ajax()) {
            $listData = [];
            foreach ($info as $list) {
                $item = [
                    'enquiry_id'        => $list->id,
                    'unit_price'        => $list->price,
                    'name'              => $list->title,
                    'minnum'               => $list->minimum_order,
                    'number'            => $list->amount,
                    'supplier_address1' => Area::where('id', $list->province_id)->first()->name,
                    'supplier_address2' => Area::where('id', $list->city_id)->first()->name,
                    'release_date'      => date('Y-m-d', strtotime($list->created_at))
                ];
                $listData[] = $item;
            }
            return response()->json([
                'data'           => $listData,
                'pagingConfData' => [
                    'page'    => $info->currentPage(),
                    'pageSize' => $request->query('pageSize'),
                    'total'   => $info->total(),
                ],]);
        }

        return view('host/provider')->with('cid', $cid)->with('pid', $pid);
    }

    /**
     * 保存询盘信息到数据库
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function postSave(Request $request)
    {
        try {
            if (Auth::user()->class == 2) {

                $validator = Validator::make(
                    $request->except(['_token']),
                    [
                        'contact_name'  => 'required',
                        'amount'        => "required|numeric|max:$request->input('max_num')",
                        'contact_phone' => 'required|numeric',
                        'price' => 'required|numeric',
                        'province'      => 'required|exists:areas,id,level,1',
                        'city'          => 'required|exists:areas,id,level,2',
                        'county'        => 'required|exists:areas,id,level,3'
                    ]
                );
              /*  if ($validator->fails()) {
                    return redirect()->back();
                }*/
                \DB::transaction(function () use ($request) {

                    $data = $request->only([
                        'amount',
                        'contact_name',
                        'contact_phone',
                        'province_id',
                        'city_id',
                        'county_id',
                        'price',

                    ]);// 只取这些数据

                    $counterOffer = CounterOffer::create($data);
                    $offer = Offer::findOrFail($request->input('offer_id'));

                    $offer->counter()->save($counterOffer);
                    //TODO 这里数据库的值减少 是在这里减还是应该审核过后再减？
                    Auth::user()->counters()->save($counterOffer);
                    Offer::where('id',
                        $request->input('offer_id'))->decrement('amount', $request->input('amount'));
                });
                return redirect()->back();
            } else {
                return redirect()->back();
            }
        } catch (UserTypeException $e) {
            return response('error', 403);
            throw $e;
        }
    }
}

